import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_dropdown.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_header.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class RoomSummary extends StatefulWidget {
  const RoomSummary({super.key});

  @override
  State<StatefulWidget> createState() => _RoomSummaryState();
}

class _RoomSummaryState extends State<RoomSummary> {
  final ScrollController _scrollController = ScrollController();
  final List<FilterHeaderItem> _headerItems = [
    FilterHeaderItem(title: "类型"),
    FilterHeaderItem(
      title: "数量：0",
      render: (title) {
        return Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        );
      },
    ),
  ];
  final List _type = [
    {"name": "全部", "value": ""},
    {"name": "无待收账单房间", "value": "1"},
    {"name": "今日入住", "value": "2"},
    {"name": "7日入住", "value": "3"},
    {"name": "30日入住", "value": "4"},
  ];

  Map _filter = {
    "pageNum": 1,
    "pageSize": 10,
    "enterType": "",
  };
  List _list = [];
  double _dueInTotalMoney = 0;
  int _total = 0;


  Widget _littleRow({ required String label, required String value }) {
    return Row(
      children: [
        Text("$label：", style: const TextStyle(fontSize: 12),),
        Text(value, style: const TextStyle(fontSize: 12),),
      ],
    );
  }

  double _toDouble(dynamic data) {
    try {
      if (data is int || data is num) {
        return data.toDouble();
      } else if (data is String) {
        return double.parse(data);
      } else if (data is double) {
        return data;
      }
    } catch (error) {
      print("toDouble error:>>>>> $error");
    }

    return 0;
  }

  Widget _renderEmpty() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(Icons.hourglass_empty_outlined, color: ThemeVars.colorPrimaryLight, size: 80,),
          SizedBox(height: 50,),
          Text("温馨提示：可以在【入住详情】中添加待收账单", style: TextStyle(fontSize: 12, color: ThemeVars.colorTextSec),),
        ],
      ),
    );
  }

  void _getBillList() async {
    try {
      EasyLoading.show();
      Map<String, dynamic> params = { ..._filter };
      Map resData = await billApi.roomSummaryList(params);
      EasyLoading.dismiss();
      List data = resData["rows"] ?? [];
      setState(() {
        _headerItems.last.title = "数量：${resData["total"] ?? 0}";
        _list.addAll(data);
        _total = resData["total"] ?? 0;
        _dueInTotalMoney = _toDouble(resData["dueInTotalMoney"]);
      });
    } catch(error) {
      EasyLoading.dismiss();
      print(error);
    }
  }

  Future<void> _removeBill(int billId) async{
    await billApi.removeBill(billId);
    EasyLoading.showToast("删除成功");
  }

  Future<void> _refresh() async {
    setState(() {
      _list = [];
      _filter["pageNum"] = 1;
    });
    _getBillList();
  }

  void _onScroll() {
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      print("判断前：》》》${_list.length} --- $_total");
      if (_list.length < _total) {
        setState(() {
          _filter["pageNum"] += 1;
        });
        _getBillList();
      }
    }
  }

  String formatCurrency(amount) {
    return Utils.formatCurrency(Utils.toDouble(amount));
  }

  @override
  void initState() {
    super.initState();
    _refresh();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      child: FilterLayout(
          headerItems: _headerItems,
          dropdownItems: [
            FilterDropdownItem(
              items: _type,
              itemAsString: (item) => item["name"],
              onChanged: (item) =>
                  setState(() {
                    _headerItems[0].title = item["name"];
                    _filter["enterType"] = item["value"];
                    _refresh();
                  }),
            ),
          ],
          child: Stack(
            children: [
              RefreshIndicator(
                onRefresh: _refresh,
                child: _list.isNotEmpty ? ListView.separated(
                  controller: _scrollController,
                  padding: const EdgeInsets.all(ThemeVars.paddingPage),
                  itemCount: _list.length,
                  itemBuilder: (context, index) {

                    Map item = _list[index];
                    Map room = item["room"];
                    return Container(
                      decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                      ),
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {

                        },
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
                              child: Text("${room["buildingName"]}${room["name"]}", style: const TextStyle(fontSize: 16), textAlign: TextAlign.left,),
                            ),
                            const SolidDivider(padding: EdgeInsets.only(left: ThemeVars.paddingPage),),
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: ThemeVars.paddingPage),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: [
                                  Row(
                                    children: [
                                      Expanded(flex: 4, child: _littleRow(label: "已收", value: "${item["completeCount"]}笔"),),
                                      Expanded(flex: 6, child: _littleRow(label: "已收金额", value: "${formatCurrency(item["completePrice"])}元"),),
                                    ],
                                  ),
                                  SizedBox(height: 4,),
                                  Row(
                                    children: [
                                      Expanded(flex: 4, child: _littleRow(label: "待收", value: "${item["incompleteCount"]}笔"),),
                                      Expanded(flex: 6, child: _littleRow(label: "待收金额", value: "${formatCurrency(item["incompletePrice"])}元",)),
                                    ],
                                  ),
                                  SizedBox(height: 4,),
                                  _littleRow(label: "租期", value: "${DateTools.formatYMD(item["checkInStart"])} - ${DateTools.formatYMD(item["checkInEnd"])}"),
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context, index) => const SizedBox(height: 15),
                )
                    : _renderEmpty(),
              ),
            ],
          )
      ),
    );
  }

}